<template>
  <ul class="todo-main">
    <!-- <h1>{{this.todoList[0].done}}</h1> -->
        <Item v-for="todo in todoList" :key="todo.id" v-bind="todo"
        @checked='checkdeHandle(todo.id)'
        @delete='deleteHandle(todo.id)'
        />
      </ul>
</template>

<script>

import Item from './Item'
export default {
name:'List',
components:{
    Item
},
data(){
    return{
        todoList:[]
            
       
    }
},
mounted(){
    this.todoList=JSON.parse(localStorage.getItem('todoList')||'[]')
    //给$bus绑定一个接受header组件传值的事件newTodo

    this.$bus.$on('newtodo',(newtodo)=>{
        this.todoList.unshift(newtodo)
    });

    //注意 因为绑定和调用都在mounted里,目前可能会有问题,未来肯定没有问题,因为未来调用事件传值,肯定是在ajax异步请求数据回来之后,才传值的
    //调用$bus上的getTodos事件,给footer传递todolist
    this.$bus.$emit('getTodos',this.todoList);

    // 全选事件newdone
    this.$bus.$on('newdone',(value)=>{
        this.todoList=this.todoList.map((item)=>{
            return {...item,done:value}
        })
    });

    // 删除已选择
    this.$bus.$on('Alldelete',()=>{
         this.todoList=this.todoList.filter((item)=>{
            return !item.done
        })
    })

},

watch:{
    todoList:{
        deep:true,
        handler(){
            localStorage.setItem('todoList',JSON.stringify(this.todoList))
            this.$bus.$emit('getTodos',this.todoList);

        }
    }
},
methods:{
    // 给子组件绑定一个单个done状态改变事件
    checkdeHandle(id){
        // console.log(id);
         this.todoList=this.todoList.map((item)=>{
            return item.id===id?{...item,done:!item.done}:item
        })
    },
    // 给子组件绑定单个删除事件
    deleteHandle(id){
        this.todoList=this.todoList.filter((item)=>{
            return item.id!==id
        })
    }
}
}
</script>

<style scoped>
/*main*/
.todo-main {
  margin-left: 0px;
  border: 1px solid #ddd;
  border-radius: 2px;
  padding: 0px;
}

.todo-empty {
  height: 40px;
  line-height: 40px;
  border: 1px solid #ddd;
  border-radius: 2px;
  padding-left: 5px;
  margin-top: 10px;
}

</style>